package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.constant.PublishConstants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.PAskCoupon;
import com.ruoyi.system.domain.PAskCouponLog;
import com.ruoyi.system.domain.bo.PAskCouponLogBo;
import com.ruoyi.system.domain.vo.PAskCouponLogVo;
import com.ruoyi.system.mapper.PAskCouponLogMapper;
import com.ruoyi.system.mapper.PAskCouponMapper;
import com.ruoyi.system.service.IPAskCouponLogService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 领取优惠券记录Service业务层处理
 *
 * @author ruoyi
 * @date 2022-07-29
 */
@RequiredArgsConstructor
@Service
public class PAskCouponLogServiceImpl implements IPAskCouponLogService {

    private final PAskCouponLogMapper baseMapper;
    private final PAskCouponMapper couponMapper;

    /**
     * 查询领取优惠券记录
     */
    @Override
    public PAskCouponLogVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询领取优惠券记录列表
     */
    @Override
    public TableDataInfo<PAskCouponLogVo> queryPageList(PAskCouponLogBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<PAskCouponLog> lqw = buildQueryWrapper(bo);
        Page<PAskCouponLogVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询领取优惠券记录列表
     */
    @Override
    public List<PAskCouponLogVo> queryList(PAskCouponLogBo bo) {
        LambdaQueryWrapper<PAskCouponLog> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<PAskCouponLog> buildQueryWrapper(PAskCouponLogBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<PAskCouponLog> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getCouponId() != null, PAskCouponLog::getCouponId, bo.getCouponId());
        lqw.eq(bo.getCid() != null, PAskCouponLog::getCid, bo.getCid());
        lqw.eq(bo.getUid() != null, PAskCouponLog::getUid, bo.getUid());
        lqw.like(StringUtils.isNotBlank(bo.getName()), PAskCouponLog::getName, bo.getName());
        lqw.eq(bo.getMoney() != null, PAskCouponLog::getMoney, bo.getMoney());
        lqw.eq(bo.getMinPrice() != null, PAskCouponLog::getMinPrice, bo.getMinPrice());
        lqw.eq(StringUtils.isNotBlank(bo.getType()), PAskCouponLog::getType, bo.getType());
        lqw.eq(bo.getStatus() != null, PAskCouponLog::getStatus, bo.getStatus());
        lqw.eq(bo.getStartTime() != null, PAskCouponLog::getStartTime, bo.getStartTime());
        lqw.eq(bo.getEndTime() != null, PAskCouponLog::getEndTime, bo.getEndTime());
        lqw.eq(bo.getUseTime() != null, PAskCouponLog::getUseTime, bo.getUseTime());
        lqw.eq(bo.getUseType() != null, PAskCouponLog::getUseType, bo.getUseType());
        lqw.eq(bo.getPrimaryKey() != null, PAskCouponLog::getPrimaryKey, bo.getPrimaryKey());
        return lqw;
    }

    /**
     * 新增领取优惠券记录
     */
    @Override
    public Boolean insertByBo(PAskCouponLogBo bo) {
        PAskCouponLog add = BeanUtil.toBean(bo, PAskCouponLog.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改领取优惠券记录
     */
    @Override
    public Boolean updateByBo(PAskCouponLogBo bo) {
        PAskCouponLog update = BeanUtil.toBean(bo, PAskCouponLog.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(PAskCouponLog entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除领取优惠券记录
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public TableDataInfo<PAskCouponLog> queryPageMyList(String userType, PageQuery pageQuery) {
        QueryWrapper<Object> lqw = Wrappers.query();
        lqw.eq("l.del_flag", UserConstants.USER_NORMAL);
        lqw.eq(StringUtils.isNotBlank(userType), "l.use_type", userType);
        lqw.eq("l.uid", LoginHelper.getUserId());
        Page<PAskCouponLog> result = baseMapper.selectVoMyPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertByFont(PAskCouponLog bo) {
        Long userId = LoginHelper.getUserId();
        // 校验是否领取该优惠券
        Long couponId = bo.getCouponId();
        PAskCoupon coupon = couponMapper.selectById(couponId);
        if (ObjectUtil.isEmpty(coupon)) {
            throw new ServiceException("非法优惠券！");
        }

        List<PAskCouponLog> logs = baseMapper.selectList(new LambdaQueryWrapper<PAskCouponLog>()
            .eq(PAskCouponLog::getUid, userId).eq(PAskCouponLog::getCouponId, couponId));
        if (CollectionUtil.isNotEmpty(logs)) {
            throw new ServiceException("你已领取过该优惠券！");
        }
        // 校验优惠券是否剩余
        String isLimited = coupon.getIsLimited();
        if (PublishConstants.COMMON_YES.equals(isLimited)) {
            int total = coupon.getTotal();
            int lastTotal = coupon.getLastTotal();
            int count = lastTotal + 1;
            if (count > total) {
                throw new ServiceException("该优惠券已被抢完！");
            }

            coupon.setLastTotal(count);
            couponMapper.updateById(coupon);
        }

        bo.setUid(userId);

        baseMapper.insert(bo);
    }
}
